import React from 'react';
import {Form,Input,Button,Select,message} from 'antd'
import { useEffect } from 'react';

import {role_list,staff_add} from '../utils/api.js'
import { useState } from 'react';
import { useHistory } from 'react-router-dom';

const { Option } = Select;

function Register(props) {
    var history=useHistory()
    //验证通过时 调用
    var onFinish = (values)=>{
        staff_add( values ).then((res)=>{
            if( res.data.code === 200 ){
                
                message.success(res.data.msg)
                setTimeout(function timer() {
 
                    history.push('/login')
               
                }, 1000)
              
                
            }else{
                message.error(res.data.msg)
            }
        })
    }

    //引入组件状态
    var [rolelist ,setRolelist ] = useState([])

    //引入组件生命周期函数
    useEffect(()=>{
        role_list().then((res)=>{
            console.log(res.data.list[0]);
            setRolelist( res.data.list )
        })
    },[])

    return (
        <div className='register'>
            
            <Form  onFinish={onFinish}>
            <div className='register_1'>用户注册</div>
                <Form.Item label="账号" name="user" rules={[{
                    required: true,
                    message: '输入账号',
                    }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="姓名" name="name" rules={[{
                    required: true,
                    message: '输入姓名',
                    }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="昵称" name="nickname" rules={[{
                    required: true,
                    message: '输入昵称',
                    }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="手机号" name="phone" rules={[{
                    required: true,
                    message: '输入手机号',
                    }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="角色" name="role" rules={[{
                    required: true,
                    message: '选择角色',
                    }]}>
                    <Select defaultValue={'选择角色'} style={{ width: 120 }} >
                        {
                            rolelist.map((item,index)=>{
                                return (
                                    <Option value={item._id} key={index}> {item.name} </Option>
                                )
                            })
                        }
                    </Select>
                </Form.Item>
                
                <Form.Item >
                    <Button type="primary" htmlType="submit">
                        注册
                    </Button>
                    <a href="http://localhost:3000/login">已有账号去登陆!</a>
                </Form.Item>
            </Form>
        </div>
    );
}

export default Register;